﻿using System;
using System.Net;
using System.Threading;

namespace Server
{
  abstract class TRequestProcessor
  {
    protected HttpListenerContext   Context;
    protected HttpListenerRequest   Request;
    protected HttpListenerResponse  Response;

    protected readonly System.Text.Encoding Encoding = System.Text.Encoding.UTF8;

    protected void Output(byte[] Buffer)
    {
      Response.ContentLength64 = Buffer.Length;
      Response.ContentEncoding = Encoding;
      Response.ContentType = "text/html";

      System.IO.Stream output = Response.OutputStream;
      output.Write(Buffer, 0, Buffer.Length);
      output.Close();
    }

    protected abstract void ProcessRequest(object Param);

    public static void CreateProcessor(HttpListenerContext Context)
    {
      TRequestProcessor Processor;
      if (Context.Request.Url.LocalPath.StartsWith("/data"))
        Processor = new TDataProcessor();
      else
        Processor = new TFileProcessor();

      Processor.Context  = Context;
      Processor.Request  = Context.Request;
      Processor.Response = Context.Response;

      ThreadPool.QueueUserWorkItem(Processor.ProcessRequest);
    }
  }
}
